/**
 * 
 */
package fr.cephb.swing;

import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

/**
 * Implementation of XAbstractTableModel for a type T.
 * This class holds a vector of object of type T
 *
 */
public abstract class GenericTableModel<T> extends XAbstractTableModel
	{
	private static final long serialVersionUID = 1L;
	private Vector<T> items=null;
	
	public GenericTableModel()
		{
		this.items= new Vector<T>();
		}
	
	public GenericTableModel(Collection<T> collection)
		{
		this.items= new Vector<T>(collection);
		}
	public GenericTableModel(T array[])
		{
		this.items= new Vector<T>(array.length);
		for(T i:array) this.items.add(i);
		}
	
	
	public GenericTableModel(Iterator<T> iter)
		{
		this();
		while(iter.hasNext()) this.items.addElement(iter.next());
		}
	
	protected Vector<T> getDataVector()
		{
		return this.items;
		}
	
	/* (non-Javadoc)
	 * @see javax.swing.table.TableModel#getColumnCount()
	 */
	@Override
	public abstract int getColumnCount();

	/* (non-Javadoc)
	 * @see javax.swing.table.TableModel#getRowCount()
	 */
	@Override
	public int getRowCount() {
		return getDataVector().size();
		}

	/** return index-th element */
	public T elementAt(int index)
		{
		return getDataVector().elementAt(index);
		}
	
	/**
	 * calls getValueOf 
	 */
	@Override
	public Object getValueAt(int rowIndex, int columnIndex)
		{
		T item= elementAt(rowIndex);
		if(item==null) return null;
		return getValueOf(item,columnIndex);
		}
	
	/** add a new element in the table and fire the listeners */
	public void addElement(T e)
		{
		getDataVector().addElement(e);
		fireTableRowsInserted(getRowCount()-1,getRowCount()-1);
		}
	
	/** remove a all elements in the table and fire the listeners */
	public void removeAll()
		{
		if(getRowCount()==0) return;
		int i=getRowCount();
		getDataVector().clear();
		fireTableRowsDeleted(0, i-1);
		}
	
	/** add  all elements from a collection and fire the listeners */
	public void addAll(Collection<T> all)
		{
		if(all.isEmpty()) return;
		int i= getRowCount();
		for(T t:all)
			{
			getDataVector().addElement(t);
			}
		fireTableRowsInserted(i,getRowCount()-1);
		}
	
	/** for a given object, returns its feature at the index-th colum */
	public abstract Object getValueOf(T item, int columnIndex);
	}
